package com.starbaba.module.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSONObject;
import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.module.model.ActivityModelVO;
import com.starbaba.module.model.LoanContentActivity;
import com.starbaba.module.model.LoanContentActivityVars;
import com.starbaba.module.model.ModuleContentItem;
import com.starbaba.module.model.ActivityModel;
import com.starbaba.module.service.INewModelService;
import com.starbaba.tools.sequence.Sequence;

@SuppressWarnings({"unchecked", "rawtypes","deprecation"})
public class LoanActivityModuleAction extends BaseAction implements ModelDriven<ModuleContentItem> {

    private static final long serialVersionUID = -4086540846138435455L;

    final BaseDao dao = new BaseDao(Constant.POOL_LIFE);

    private ModuleContentItem model;

    private INewModelService service;

    @Autowired
    @Qualifier("newModelServiceImpl")
    public void setService(INewModelService service) {
        this.service = service;
    }

    @Override
    public ModuleContentItem getModel() {
        if (model == null) {
            model = new ModuleContentItem();
        }
        return model;
    }

    public void modelList() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        parsePageRequest();
        PageResponse pageResponse = new PageResponse();
        int start = pageRequest.getIDisplayStart();
        int length = pageRequest.getIDisplayLength();
        List list = service.getDataList(start, length, pageResponse, paramsMap);
        pageResponse.setAaData(list);
        pageResponse.setSEcho(pageRequest.getSEcho());

        try {
            sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
        } catch (IOException e) {
            LogService.error(e);
        }
    }

    public void saveModule() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        ActivityModel model = new ActivityModel();
        String modelName = (String) paramsMap.get("modelName");
        String modelRemark = (String) paramsMap.get("modelRemark");
        String modelType = (String) paramsMap.get("modelType");
        String target_url = (String) paramsMap.get("target_url");
        Long modelId = Sequence.getSequence();
        model.setId(modelId);
        model.setModelName(modelName);
        model.setModelRemark(modelRemark);
        model.setModelType(Integer.parseInt(modelType));
        model.setCtime(new Date());
        model.setTarget_url(target_url);
        try {
            dao.add(model);
        } catch (AppException e1) {
            responseError(e1);
            e1.printStackTrace();
        }

        String indexTxt = (String) paramsMap.get("index");
        if (!StringUtils.isEmpty(indexTxt)) {
            Integer index = Integer.parseInt(indexTxt);
            for (int i = 0; i < index; i++) {
                ModuleContentItem contentItem = new ModuleContentItem();
                String name = (String) paramsMap.get("name" + i);
                String content = (String) paramsMap.get("content" + i);
                String type = (String) paramsMap.get("type" + i);
                String remark = (String) paramsMap.get("remark" + i);
                contentItem.setContent(content);
                contentItem.setName(name);
                contentItem.setType(Integer.parseInt(type));
                if (!StringUtils.isEmpty(remark)) {
                    contentItem.setRemark(remark);
                }
                contentItem.setSort(i);
                contentItem.setModelId(modelId);
                try {
                    dao.add(contentItem);
                } catch (AppException e) {
                    responseError(e);
                    e.printStackTrace();
                }
            }
        }
        responseSuccess();
    }

    private void responseSuccess() {
        JsonObject result = new JsonObject();
        result.add("result", new ResultJson().toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     *
     * @Title responseSuccess
     * @Description <p>
     *              返回错误信息
     *              </p>
     *              　　　　　
     * @author zhengjunjie
     * @dateTime 2015年10月16日 下午2:26:53
     *
     */
    private void responseError(Exception error) {
        StringWriter writer = new StringWriter();
        error.printStackTrace(new PrintWriter(writer, true));
        ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
        JsonObject result = new JsonObject();
        result.add("result", resultJson.toJSON());
        try {
            sendJsonMessage(result.toString());
        } catch (Exception e) {
            LogService.error(e);
        }
    }

    public void getModelData() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        try {
            String idTxt = (String) paramsMap.get("id");
            if (!StringUtils.isEmpty(idTxt)) {
                ActivityModelVO activityModelVO = new ActivityModelVO();
                Long id = Long.parseLong(idTxt);
                ActivityModel activityModel = dao.get("select * from activity_model where id =?", ActivityModel.class, id);
                List<ModuleContentItem> itemList = dao.list("select * from module_content_item where modelId=? order by sort asc", ModuleContentItem.class, id);
                activityModelVO.setActivityModel(activityModel);
                activityModelVO.setItemList(itemList);
                sendJsonMessage(JsonUtils.toJson(activityModelVO, null, true, null, false));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void editModule() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);

        ActivityModel model = new ActivityModel();
        String modelName = (String) paramsMap.get("modelName");
        String modelRemark = (String) paramsMap.get("modelRemark");
        String modelType = (String) paramsMap.get("modelType");
        String target_url = (String) paramsMap.get("target_url");

        String idTxt = (String) paramsMap.get("id");
        boolean flag = false;
        Long id = null;
        if (StringUtils.isEmpty(idTxt)) {
            flag = true;
            id = Sequence.getSequence();
        } else {
            id = Long.parseLong(idTxt);
        }

        model.setId(id);
        model.setModelName(modelName);
        model.setModelRemark(modelRemark);
        model.setModelType(Integer.parseInt(modelType));
        model.setTarget_url(target_url);
        model.setCtime(new Date());
        try {
            if (flag) {
                dao.add(model);
            } else {
                dao.update(model, new String[] { "id" });
                dao.update("delete from module_content_item where modelId = ?", id);
            }

        } catch (AppException e1) {
            responseError(e1);
            e1.printStackTrace();
        }

        String indexTxt = (String) paramsMap.get("index");
        if (!StringUtils.isEmpty(indexTxt)) {
            Integer index = Integer.parseInt(indexTxt);
            for (int i = 0; i < index; i++) {
                ModuleContentItem contentItem = new ModuleContentItem();
                String name = (String) paramsMap.get("name" + i);
                String content = (String) paramsMap.get("content" + i);
                String type = (String) paramsMap.get("type" + i);
                String remark = (String) paramsMap.get("remark" + i);
                contentItem.setContent(content);
                contentItem.setName(name);
                contentItem.setType(Integer.parseInt(type));
                if (!StringUtils.isEmpty(remark)) {
                    contentItem.setRemark(remark);
                }
                contentItem.setSort(i);
                contentItem.setModelId(id);
                try {
                    dao.add(contentItem);
                } catch (AppException e) {
                    responseError(e);
                    e.printStackTrace();
                }
            }
        }

        responseSuccess();

    }
    
    public void delActivity() {
    	paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        String id = (String) paramsMap.get("id");
        service.delActivity(id);
        JSONObject obj = new JSONObject();
        obj.put("success", "true");
        try {
            sendJsonMessage(JsonUtils.toJson(obj, null, true, null, false));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void copyModel() {
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        String userId = userVO.getUserid();
		String userName = userVO.getUsername();
        String activityId = (String) paramsMap.get("id");
        service.copyModel(userId, userName, activityId);
        JSONObject obj = new JSONObject();
        obj.put("success", "true");
        try {
            sendJsonMessage(JsonUtils.toJson(obj, null, true, null, false));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void copytotest() {
        BaseDao dao = new BaseDao(Constant.POOL_LIFE);// 正式数据库
        BaseDao testdao = new BaseDao(Constant.POOL_PUSH_RW);// 测试数据库
        paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
        String id = (String) paramsMap.get("id");

        try {
            if (!StringUtils.isEmpty(id)) {
                String activitySql = "select * from loan_content_activity where id =?";
                LoanContentActivity activity = dao.get(activitySql, LoanContentActivity.class, id);
                int count = testdao.getInt(activitySql, id);
                if (count > 0) {
                    responseError(new AppException(-1, "该ID已在测试库存在"));
                    return;
                }
                testdao.add(activity);
                String activityVars = "select * from loan_content_activity_vars where aid =?";
                List<LoanContentActivityVars> contentList = dao.list(activityVars, LoanContentActivityVars.class, id);
                for (LoanContentActivityVars var : contentList) {
                    testdao.add(var);
                }

            }
            responseSuccess();
        } catch (Exception e) {
            responseError(e);
        }
    }

    public void saveSort() {

    }

}
